from fisheye_manager import FisheyeManager
import fisheye_consts
from packet import PacketState

class PacketManager:
    # A singleton PacketManager class which is responsible for the low-level logic of transferring packets.
    instance = {} 
    
    def __init__(self): 
        if self.__class__ not in PacketManager.instance:
            PacketManager.instance[self.__class__] = PacketManager.__InnerSingeton()
        else :
            pass

    def __getattr__(self, name):
        return getattr(self.instance[self.__class__], name)

    def __setattr__(self, name, value):
        return setattr(self.instance[self.__class__], name, value)
    
    # The real Singleton class (inner class)
    class __InnerSingeton:
        def __init__(self):
            """
            Constructor.
            """
            pass
            
        def send(self, packet, next_hop_node_id, battery_manager):
            """
            Added the packet to the queue of the next_hop_node.
            """
            try:
                battery_manager.validate_send(next_hop_node_id, packet.get_packet_size())
            except Exception, ex:
                print ex
                packet.mark_sent = PacketState.NOT_ENOUGH_BATTERY
                return False

            #Packet has passed another hop.
            packet.num_hops += 1

            # packet is moved to another queue- mark it as unhandled so the next queue will work on it.
            # packet.mark_sent = PacketState.UNHANDLED
            if FisheyeManager().get_node_object_by_id(next_hop_node_id).add_packet_to_queue(packet) == False:
                packet.mark_sent = PacketState.QUEUE_FULL
                return False

            return True